import {
	base64_encode,
	base64_decode
} from './base64';
import md5 from './md5';
import store from '@/store';

//#ifdef MP
// 小程序端执行
import siteInfo from '../../siteinfo.js'
//#endif

//#ifdef H5
import siteInfoH5 from '../../siteinfoH5.js'
//#endif

var util = {};

util.m = 'muu_classroom';

/**
 * IOS小程序判断显示购买价格及按钮
 */
util.setShowSale = function(){
	let systemInfo = uni.getStorageSync('systemInfo');
	//仅在微信小程序端执行
	// #ifdef MP
	if(systemInfo.system.search("iOS") != -1){
		return false;
	}
	// #endif
	return true;
},

/**
	构造微擎地址, 
	@params action 微擎系统中的controller, action, do，格式为 'wxapp/home/navs'
	@params querystring 格式为 {参数名1 : 值1, 参数名2 : 值2}
*/
util.url = function (action, querystring) {

	//#ifdef MP
	var url = siteInfo.siteroot + '?i=' + siteInfo.uniacid + '&t=' + siteInfo.multiid + '&v=' + siteInfo.version + '&';
	//#endif
	
	//#ifdef H5
	var url = siteInfoH5.siteroot + '?i=' + siteInfoH5.uniacid + '&';
	//#endif
	if (action) {
		action = action.split('/');
		if (action[0]) {
			url += 'c=' + action[0] + '&';
		}
		if (action[1]) {
			url += 'a=' + action[1] + '&';
		}
		if (action[2]) {
			url += 'do=' + action[2] + '&';
		}
		var sessionid = uni.getStorageSync('userInfo').sessionid;
		var state = getUrlParam(url, 'state');
		if (!state && sessionid) {
			url += 'state=we7sid-' + sessionid + '&';
		}
	}
	if (querystring && typeof querystring === 'object') {
		for (let param in querystring) {
            if (param && querystring.hasOwnProperty(param) && querystring[param]) {
				url += param + '=' + querystring[param] + '&';
			}
		}
	}
	
	return url;
}

/**
 * 删除指定url参数
 * @param {Object} url
 * @param {Object} name
 */
util.urlDelP = function(url, name){
    var urlArr = url.split('?');
    if (urlArr.length > 1 && urlArr[1].indexOf(name) > -1) {
        var query = urlArr[1];
        var obj = {}
        var arr = query.split("&");
        for (var i = 0; i < arr.length; i++) {
            arr[i] = arr[i].split("=");
            obj[arr[i][0]] = arr[i][1];
        };
        delete obj[name];
        var urlte = urlArr[0] + '?' + JSON.stringify(obj).replace(/[\"\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
        return urlte;
    } else {
        return url;
    };
}

/*
* 获取链接某个参数
* url 链接地址
* name 参数名称
*/
function getUrlParam(url, name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象  
	var r = url.split('?')[1].match(reg);  //匹配目标参数  
	if (r != null) return unescape(r[2]); return null; //返回参数值  
}

/**
 * 设置缓存和过期时间
 */
util.muuCache = function(key, value, expiration = 600) {
	let nowTime = Date.parse(new Date()) / 1000;
	if (key && value) {
		let expire = nowTime + Number(expiration);
		uni.setStorageSync(key, JSON.stringify(value) + '|_muu_|' + expire)
		//console.log('已经把' + key + '存入缓存,过期时间为' + expire)
	} else if (key && !value) {
		let val = uni.getStorageSync(key);
		if (val) {
			// 缓存存在，判断是否过期
			let temp = val.split('|_muu_|')
			if (!temp[1] || temp[1] <= nowTime) {
				uni.removeStorageSync(key)
				console.log(key + '缓存已失效')
				return '';
			} else {
				return JSON.parse(temp[0]);
			}
		}
	}
}

/**
 * url参数ENCODE
 * @param {Object} param
 * @param {Object} key
 * @param {Object} encode
 */
util.urlEncode = function(param, key, encode) {
	if (param==null) return '';
	var paramStr = '';
	var t = typeof (param);
	if (t == 'string' || t == 'number' || t == 'boolean') {
		paramStr += '&' + key + '='  + ((encode==null||encode) ? encodeURIComponent(param) : param); 
	} else {
		for (var i in param) {
			var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
			paramStr += this.urlEncode(param[i], k, encode)
		}
	}
	return paramStr;
}

/**
 * 路由至页面
 */
util.goToLink = function(link,index){
	//console.log(link)
	
	if(index !== undefined){
		store.commit('setPageIndex',index)
	}else{
		index = null
		store.commit('setPageIndex',index)
	}
	var module = util.m;
	//初始化url路由地址，默认首页
	if(link.type == 'index'){ //首页
		let url = '../../../'+ module +'/pages/index/index'
		uni.redirectTo({
			url: url
		});
	}
	if(link.type == 'user'){ //用户中心
		let url = '../../../'+ module +'/pages/my/index'
		//console.log(url)
		uni.redirectTo({
			url: url
		});
	}
	if(link.type == 'category'){ //分类页
		let url = '../../../'+ module +'/pages/category/list'
		uni.navigateTo({
			url: url
		});
	}
	if(link.type == 'member'){ //会员页
		let url = '../../../'+ module +'/pages/member/list'
		uni.navigateTo({
			url: url
		});
	}
	if(link.type == 'micro_page'){ //自定义页面
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/customPage/index?' + urlParams
		// #ifdef MP
		uni.redirectTo({
			url: url
		});
		// #endif
		// #ifdef H5
		uni.navigateTo({
			url: url
		});
		// #endif
	}
	
	if(link.type == 'knowledge_list'){ //点播课程列表
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/knowledge/lists?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	if(link.type == 'knowledge_detail'){ //点播课程详情
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/knowledge/detail?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	if(link.type == 'column_list'){ //专栏课程列表
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/column/lists?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	if(link.type == 'column_detail'){ //专栏课程详情
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/column/detail?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	
	if(link.type == 'offline_list'){ //线下课程列表
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/offline/lists?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	if(link.type == 'offline_detail'){ //线下课程详情
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/offline/detail?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	
	if(link.type == 'material_list'){ //资料下载列表
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/material/lists?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	if(link.type == 'material_detail'){ //资料下载详情
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/material/detail?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	
	if(link.type == 'exam_paper_list'){ //试卷列表
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/exam/paper/lists?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	if(link.type == 'exam_paper_detail'){ //试卷详情
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/exam/paper/detail?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	
	if(link.type == 'goods_list'){ //云小店商品列表
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/goods/lists?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	if(link.type == 'goods_detail'){ //云小店商品详情
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/goods/detail?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	
	if(link.type == 'activity_list'){ //线下活动列表
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/activity/lists?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	
	if(link.type == 'activity_detail'){ //线下活动详情
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/activity/detail?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	
	if (link.type == 'forum_list') { //外部链接至webview
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../' + module + '/pages/forum/lists?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	if (link.type == 'forum_detail') { //外部链接至webview
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../' + module + '/pages/forum/detail?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	if (link.type == 'post_detail') { //外部链接至webview
		let params = link.param
		let urlParams = util.urlEncode(params)
		let url = '../../../' + module + '/pages/forum/post/detail?' + urlParams
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
	}
	
	if(link.type == 'out_url'){ //外部链接至webview
		let params = link.param
		console.log('out_url',params)
		let urlParams = util.urlEncode(params)
		let url = '../../../'+ module +'/pages/detail/index?' + urlParams
		//#ifdef MP-WEIXIN
		//指定跳转地址
		uni.navigateTo({
			url: url
		});
		//#endif
		//#ifdef H5
		location.href = params.url
		//#endif

	}
}

/**
	二次封装微信wx.request函数、增加交互体全、配置缓存、以及配合微擎格式化返回数据

	@params option 弹出参数表，
	{
		url : 同微信,
		data : 同微信,
		header : 同微信,
		method : 同微信,
		success : 同微信,
		fail : 同微信,
		complete : 同微信,

		cachetime : 缓存周期，在此周期内不重复请求http，默认不缓存
	}
*/
util.request = function (option) {
	var _ = require('./underscore.js');
	var md5 = require('md5.js');
	var app = getApp();
	var option = option ? option : {};
		option.cachetime = option.cachetime ? option.cachetime : 0;
	
	var url = option.url;
	if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
		url = util.url(url);
	}
	
	if (option.data.action) {
		url = url + '&action=' + option.data.action;
	}
	if (!option.data.m) {
		var nowPage = getCurrentPages();
		//console.log(nowPage);
		if (nowPage.length) {
			nowPage = nowPage[getCurrentPages().length - 1];
			if (nowPage && nowPage.route) {
				url = url + '&m=' + nowPage.route.split('/')[0];
			}
		}
	}else{
		url = url + '&m=' + option.data.m;
	}
	
	if (!url) {
		return false;
	}
	
	// 分销商参数
	let promoter_uid = uni.getStorageSync('promoter_uid')
	if(promoter_uid){
		option.data.promoter_uid = promoter_uid
	}

	uni.request({
		'url': url,
		'data': option.data ? option.data : {},
		// #ifdef H5
		'header': option.header ? option.header : {
			'content-type': 'application/x-www-form-urlencoded',
			'X-Requested-With': 'XMLHttpRequest',
		},
		// #endif
		// #ifdef MP
		'header': option.header ? option.header : {
			'content-type': 'application/x-www-form-urlencoded',
		},
		// #endif
		'method': option.method ? option.method : 'GET',
		'dataType': 'json',
		'success': function (response) {
			if(response.data.code == 0 && response.data.data == 'login'){
				// #ifdef H5
				if(util.isWechat() == true){
					util.login()
				}
				// #endif
			}
			if (response.data.errno) {
				if (response.data.errno == '41009') {
					console.log('接口返回错误')
					uni.setStorage({
						'key': 'userInfo',
						'data': '',
						'success': function(){
							uni.setStorageSync('openid', '');
							// 递归重新执行自身
							util.request(option)
						}
					});
				} else {
					if (option.fail && typeof option.fail == 'function') {
						option.fail(response);
					} else {
						if (response.data.message) {
							if (response.data.data != null && response.data.data.redirect) {
								var redirect = response.data.data.redirect;
							} else {
								var redirect = '';
							}
							app.util.message(response.data.message, redirect, 'error');
						}
					}
					return;
				}
			} else {
				if (option.success && typeof option.success == 'function') {
					option.success(response);
				}
				//写入缓存，减少HTTP请求，并且如果网络异常可以读取缓存数据
				if (option.cachetime) {
					var cachedata = { 'data': response.data, 'expire': timestamp + option.cachetime * 1000 };
					uni.setStorageSync(cachekey, cachedata);
				}
			}
		},
		'fail': function (response) {

			//如果请求失败，尝试从缓存中读取数据
			var md5 = require('md5.js');
			var cachekey = md5(url);
			var cachedata = uni.getStorageSync(cachekey);
			if (cachedata && cachedata.data) {
				if (option.success && typeof option.success == 'function') {
					option.success(cachedata);
				}
				console.log('failreadcache:' + url);
				return true;
			} else {
				if (option.fail && typeof option.fail == 'function') {
					option.fail(response);
				}
			}
		},
		'complete': function (response) {
			if (option.complete && typeof option.complete == 'function') {
				option.complete(response);
			}
		}
	});
}

/**
 * 重新获取用户信息
 * @param {Object} cb
 */
util.getUserInfo = function(cb){
	
	var m = m ? m : util.m;
	//#ifdef H5
	console.log('H5端')
	var userInfo = uni.getStorageSync('userInfo') || {};
	util.request({
		url : 'entry/site/ucenter',
		data : {
			action: 'user_info',
			m: m,
		},
		success: function (res) {
			
			if (res.data.code == 200) {
				//console.log(res.data.data,'用户数据')
				userInfo.memberInfo = res.data.data
				uni.setStorageSync('userInfo', userInfo)
				typeof cb == "function" && cb(userInfo);
			}
			if(res.data.code == 0) {
				typeof cb == "function" && cb();
			}
		}
	})
	//#endif
	
	//#ifdef MP
	uni.login({
		success: function (res) {
			console.log(res)
			let code = res.code
			util.request({
				url: 'entry/wxapp/session',
				data: {
					'action': 'get_openid',
					'code': code ? code : '',
					'm': 'muu_classroom',
				},
				success: function (a) {
					console.log(a);
					if (a.data.code == 200) {
						if(a.data.data.openid){
							uni.setStorageSync('openid', a.data.data.openid)
							// 持久登录
							util.request({
								url: 'entry/wxapp/session',
								data: {
									'action': 'openid',
									'openid': a.data.data.openid,
								},
								success: function (b) {
									console.log(b);
									if (b.data.code == 200) {
										let userInfo = {}
										userInfo.sessionid = b.data.data.sessionid
										userInfo.memberInfo = b.data.data.userinfo
										uni.setStorageSync('userInfo', userInfo)
									}
								}
							});
						}
					}
				}
			});
		},
	})
	typeof cb == "function" && cb();
	//#endif
}


/**
 * @param {Object} cb
 * @param {Object} code
 * @param {Object} m 模块名称
 */
util.getWe7User = function (cb, code, m) {
	var userInfo = {};
	util.request({
		url: 'entry/wxapp/session',
		data: {
			'action': 'openid',
			'code': code ? code : '',
		},
		success: function (res) {
			console.log(res);
			if (res.data.code == 200) {
				userInfo.sessionid = res.data.data.sessionid
				userInfo.memberInfo = res.data.data.userinfo
				uni.setStorageSync('userInfo', userInfo)
				if(res.data.data.openid){
					uni.setStorageSync('openid', res.data.data.openid)
				}
				
				typeof cb == "function" && cb(userInfo);
			}else{
				uni.showToast({
				    title: res.data.msg,
				    duration: 2000,
					icon: 'none'
				});
			}
		}
	});
}

util.upadteUser = function (wxInfo, m, cb) {
	//console.log(wxInfo);
	var userInfo = uni.getStorageSync('userInfo');
	if (!wxInfo) {
		return typeof cb == "function" && cb(userInfo);
	}
	
	var url = '';
	//#ifdef H5
		url = 'entry/site/ucenter';
	//#endif
	//#ifdef MP-WEIXIN
		url = 'entry/wxapp/session';
	//#endif
	//#ifdef MP-MP-TOUTIAO
		url = 'entry/toutiaoapp/session';
	//#endif
	util.request({
		url: url,
		data: {
			userInfo: JSON.stringify(wxInfo.userInfo),
			m: m,
			action: 'userinfo'
		},
		method: 'POST',
		cachetime: 0,
		success: function (res) {
			//console.log('更新用户信息成功');
			//console.log(res)
			if (res.data.code == 200) {
				userInfo.memberInfo = res.data.data;
				uni.setStorageSync('userInfo', userInfo);
			}
			if (res.data.code == 0) {
				uni.showToast({
					title: res.data.msg,
					icon: 'none'
				})
			}
			typeof cb == "function" && cb(userInfo);
		}
	});
}

/**
 * 获取用户信息
 * @param {Object} cb
 * @param {Object} m 模块名称
 * @param {Object} wxInfo
 */
util.login = function (cb, m, wxInfo) {
	var m = m ? m : util.m;
	// #ifdef H5
	var userInfo = {
		'sessionid': '',
		'memberInfo': '',
	};
	//console.log('h5端登录')
	var url = util.url('entry/site/oauth',{
		'm' : m
	});
	//获取当前页面完整url
	var return_url = window.location.href;
		return_url = encodeURIComponent(return_url);
		url = url + '&return_url=' + return_url
		console.log('oauth',url)
		//return false;
		//跳转网页授权登录
		window.location.href = url
	
	// #endif
	
	
	// #ifdef MP
	var login = function() {
		console.log('start login');
		var userInfo = {
			'sessionid': '',
			'wxInfo': '',
			'memberInfo': '',
		};
		uni.login({
			success: function (res) {
				console.log(res);
				util.getWe7User(function(userInfo){
					console.log(userInfo,'userInfo')
					if (uni.canIUse('getUserProfile')) {
						uni.showModal({
							title: '温馨提示',
							content: '请允许授权以便更好的为您提供服务',
							success: function (res) {
								if (res.confirm === true) {
									uni.getUserProfile({
										lang: 'zh_CN',
										desc: '用于登陆',
										success: function(wxInfo){
											//console.log(wxInfo)
											uni.setStorageSync('userInfo', userInfo)
											util.upadteUser(wxInfo, m, function(userInfo) {
												//console.log(wxInfo,'wxInfo')
												typeof cb == "function" && cb(userInfo);
											})
										},
										fail: function(res) {
											//console.log(res)
											typeof cb == "function" && cb(userInfo);
										}
									})
								}else{
									//用户取消了登录
								}
							}
						})
					} else {
						typeof cb == "function" && cb(userInfo);
					}
					
				}, res.code,m)
			},
			fail: function () {
				uni.showModal({
					title: '获取信息失败',
					content: '请允许授权以便为您提供服务',
					success: function (res) {
						if (res.confirm) {
							util.getUserInfo();
						}
					}
				})
			}
		});
	};

	var userInfo = uni.getStorageSync('userInfo') || {};
	if (userInfo.sessionid) {
		util.checkSession({
			success: function(){
				if (wxInfo) {
					util.upadteUser(wxInfo, function(userInfo) {
						typeof cb == "function" && cb(userInfo);
					})
				} else {
					typeof cb == "function" && cb(userInfo);
				}
			},
			fail: function(){
				userInfo.sessionid = '';
				console.log('relogin');
				uni.removeStorageSync('userInfo');
				login();
			}
		},m)
	} else {
		//调用登录接口
		login();
	}
	// #endif
}

util.checkSession = function(option,m) {
	util.request({
		url: 'entry/wxapp/session',
		data: {
			m: m,
			action: 'check'
		},
		method: 'POST',
		cachetime: 0,
		//showLoading: false,
		success: function (res) {
			if (!res.data.errno) {
				typeof option.success == "function" && option.success();
			} else {
				typeof option.fail == "function" && option.fail();
			}
		},
		fail: function() {
			typeof option.fail == "function" && option.fail();
		}
	})
}

/*
 * 提示信息
 * type 为 success, error 当为 success,  时，为toast方式，否则为模态框的方式
 * redirect 为提示后的跳转地址, 跳转的时候可以加上 协议名称  
 * navigate:/we7/pages/detail/detail 以 navigateTo 的方法跳转，
 * redirect:/we7/pages/detail/detail 以 redirectTo 的方式跳转，默认为 redirect
*/
util.message = function(title, redirect, type) {
	if (!title) {
		return true;
	}
	if (typeof title == 'object') {
		redirect = title.redirect;
		type = title.type;
		title = title.title;
	}
	if (redirect) {
		var redirectType = redirect.substring(0, 9), url = '', redirectFunction = '';
		if (redirectType == 'navigate:') {
			redirectFunction = 'navigateTo';
			url = redirect.substring(9);
		} else if (redirectType == 'redirect:') {
			redirectFunction = 'redirectTo';
			url = redirect.substring(9);
		} else {
			url = redirect;
			redirectFunction = 'redirectTo';
		}
	}
	console.log(url)
	if (!type) {
		type = 'success';
	}

	if (type == 'success') {
		uni.showToast({
			title: title,
			icon: 'success',
			duration: 2000,
			mask : url ? true : false,
			complete : function() {
				if (url) {
					setTimeout(function(){
						wx[redirectFunction]({
							url: url,
						});
					}, 1800);
				}
				
			}
		});
	} else if (type == 'error') {
		uni.showModal({
			title: '系统信息',
			content : title,
			showCancel : false,
			complete : function() {
				if (url) {
					wx[redirectFunction]({
						url: url,
					});
				}
			}
		});
	}
}

//封装微信等待提示，防止ajax过多时，show多次
util.showLoading = function() {
	var isShowLoading = uni.getStorageSync('isShowLoading');
	if (isShowLoading) {
		uni.hideLoading();
		uni.setStorageSync('isShowLoading', false);
	}

	uni.showLoading({
		title : '加载中',
		complete : function() {
			uni.setStorageSync('isShowLoading', true);
		},
		fail : function() {
			uni.setStorageSync('isShowLoading', false);
		}
	});
}

util.showImage = function(event) {
	var url = event ? event.currentTarget.dataset.preview : '';
	if (!url) {
		return false;
	}
	uni.previewImage({
		urls: [url]
	});
}

/**
 * 转换内容中的emoji表情为 unicode 码点，在Php中使用utf8_bytes来转换输出
*/
util.parseContent = function(string) {
	if (!string) {
		return string;
	}

	var ranges = [
			'\ud83c[\udf00-\udfff]', // U+1F300 to U+1F3FF
			'\ud83d[\udc00-\ude4f]', // U+1F400 to U+1F64F
			'\ud83d[\ude80-\udeff]'  // U+1F680 to U+1F6FF
		];
	var emoji = string.match(
		new RegExp(ranges.join('|'), 'g'));

	if (emoji) {
		for (var i in emoji) {
			string = string.replace(emoji[i], '[U+' + emoji[i].codePointAt(0).toString(16).toUpperCase() + ']');
		}
	}
	return string;
}

util.date = function(){
	/**
	 * 判断闰年
	 * @param date Date日期对象
	 * @return boolean true 或false
	 */
	this.isLeapYear = function(date){
		return (0==date.getYear()%4&&((date.getYear()%100!=0)||(date.getYear()%400==0))); 
	}
	
	/**
	 * 日期对象转换为指定格式的字符串
	 * @param f 日期格式,格式定义如下 yyyy-MM-dd HH:mm:ss
	 * @param date Date日期对象, 如果缺省，则为当前时间
	 *
	 * YYYY/yyyy/YY/yy 表示年份  
	 * MM/M 月份  
	 * W/w 星期  
	 * dd/DD/d/D 日期  
	 * hh/HH/h/H 时间  
	 * mm/m 分钟  
	 * ss/SS/s/S 秒  
	 * @return string 指定格式的时间字符串
	 */
	this.dateToStr = function(formatStr, date){
		formatStr = arguments[0] || "yyyy-MM-dd HH:mm:ss";
		date = arguments[1] || new Date();
		var str = formatStr;   
		var Week = ['日','一','二','三','四','五','六'];  
		str=str.replace(/yyyy|YYYY/,date.getFullYear());   
		str=str.replace(/yy|YY/,(date.getYear() % 100)>9?(date.getYear() % 100).toString():'0' + (date.getYear() % 100));   
		str=str.replace(/MM/,date.getMonth()>9?(date.getMonth() + 1):'0' + (date.getMonth() + 1));   
		str=str.replace(/M/g,date.getMonth());   
		str=str.replace(/w|W/g,Week[date.getDay()]);   
	  
		str=str.replace(/dd|DD/,date.getDate()>9?date.getDate().toString():'0' + date.getDate());   
		str=str.replace(/d|D/g,date.getDate());   
	  
		str=str.replace(/hh|HH/,date.getHours()>9?date.getHours().toString():'0' + date.getHours());   
		str=str.replace(/h|H/g,date.getHours());   
		str=str.replace(/mm/,date.getMinutes()>9?date.getMinutes().toString():'0' + date.getMinutes());   
		str=str.replace(/m/g,date.getMinutes());   
	  
		str=str.replace(/ss|SS/,date.getSeconds()>9?date.getSeconds().toString():'0' + date.getSeconds());   
		str=str.replace(/s|S/g,date.getSeconds());   
	  
		return str;   
	}
 
	
	/**
	* 日期计算  
	* @param strInterval string  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒  
	* @param num int
	* @param date Date 日期对象
	* @return Date 返回日期对象
	*/
	this.dateAdd = function(strInterval, num, date){
		date =  arguments[2] || new Date();
		switch (strInterval) { 
			case 's' :return new Date(date.getTime() + (1000 * num));  
			case 'n' :return new Date(date.getTime() + (60000 * num));  
			case 'h' :return new Date(date.getTime() + (3600000 * num));  
			case 'd' :return new Date(date.getTime() + (86400000 * num));  
			case 'w' :return new Date(date.getTime() + ((86400000 * 7) * num));  
			case 'm' :return new Date(date.getFullYear(), (date.getMonth()) + num, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());  
			case 'y' :return new Date((date.getFullYear() + num), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());  
		}  
	}  
	
	/**
	* 比较日期差 dtEnd 格式为日期型或者有效日期格式字符串
	* @param strInterval string  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒  
	* @param dtStart Date  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒
	* @param dtEnd Date  可选值 y 年 m月 d日 w星期 ww周 h时 n分 s秒 
	*/
	this.dateDiff = function(strInterval, dtStart, dtEnd) {   
		switch (strInterval) {   
			case 's' :return parseInt((dtEnd - dtStart) / 1000);  
			case 'n' :return parseInt((dtEnd - dtStart) / 60000);  
			case 'h' :return parseInt((dtEnd - dtStart) / 3600000);  
			case 'd' :return parseInt((dtEnd - dtStart) / 86400000);  
			case 'w' :return parseInt((dtEnd - dtStart) / (86400000 * 7));  
			case 'm' :return (dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);  
			case 'y' :return dtEnd.getFullYear() - dtStart.getFullYear();  
		}  
	}
 
	/**
	* 字符串转换为日期对象 // eval 不可用
	* @param date Date 格式为yyyy-MM-dd HH:mm:ss，必须按年月日时分秒的顺序，中间分隔符不限制
	*/
	this.strToDate = function(dateStr){
		var data = dateStr;  
		var reCat = /(\d{1,4})/gm;   
		var t = data.match(reCat);
		t[1] = t[1] - 1;
		eval('var d = new Date('+t.join(',')+');');
		return d;
	}
 
	/**
	* 把指定格式的字符串转换为日期对象yyyy-MM-dd HH:mm:ss
	* 
	*/
	this.strFormatToDate = function(formatStr, dateStr){
		var year = 0;
		var start = -1;
		var len = dateStr.length;
		if((start = formatStr.indexOf('yyyy')) > -1 && start < len){
			year = dateStr.substr(start, 4);
		}
		var month = 0;
		if((start = formatStr.indexOf('MM')) > -1  && start < len){
			month = parseInt(dateStr.substr(start, 2)) - 1;
		}
		var day = 0;
		if((start = formatStr.indexOf('dd')) > -1 && start < len){
			day = parseInt(dateStr.substr(start, 2));
		}
		var hour = 0;
		if( ((start = formatStr.indexOf('HH')) > -1 || (start = formatStr.indexOf('hh')) > 1) && start < len){
			hour = parseInt(dateStr.substr(start, 2));
		}
		var minute = 0;
		if((start = formatStr.indexOf('mm')) > -1  && start < len){
			minute = dateStr.substr(start, 2);
		}
		var second = 0;
		if((start = formatStr.indexOf('ss')) > -1  && start < len){
			second = dateStr.substr(start, 2);
		}
		return new Date(year, month, day, hour, minute, second);
	}
 
 
	/**
	* 日期对象转换为毫秒数
	*/
	this.dateToLong = function(date){
		return date.getTime();
	}
 
	/**
	* 毫秒转换为日期对象
	* @param dateVal number 日期的毫秒数 
	*/
	this.longToDate = function(dateVal){
		return new Date(dateVal);
	}
 
	/**
	* 判断字符串是否为日期格式
	* @param str string 字符串
	* @param formatStr string 日期格式， 如下 yyyy-MM-dd
	*/
	this.isDate = function(str, formatStr){
		if (formatStr == null){
			formatStr = "yyyyMMdd";	
		}
		var yIndex = formatStr.indexOf("yyyy");	 
		if(yIndex==-1){
			return false;
		}
		var year = str.substring(yIndex,yIndex+4);	 
		var mIndex = formatStr.indexOf("MM");	 
		if(mIndex==-1){
			return false;
		}
		var month = str.substring(mIndex,mIndex+2);	 
		var dIndex = formatStr.indexOf("dd");	 
		if(dIndex==-1){
			return false;
		}
		var day = str.substring(dIndex,dIndex+2);	 
		if(!isNumber(year)||year>"2100" || year< "1900"){
			return false;
		}
		if(!isNumber(month)||month>"12" || month< "01"){
			return false;
		}
		if(day>getMaxDay(year,month) || day< "01"){
			return false;
		}
		return true;   
	}
	
	this.getMaxDay = function(year,month) {	 
		if(month==4||month==6||month==9||month==11)	 
			return "30";	 
		if(month==2)	 
			if(year%4==0&&year%100!=0 || year%400==0)	 
				return "29";	 
			else	 
				return "28";	 
		return "31";	 
	}	 
	/**
	*	变量是否为数字
	*/
	this.isNumber = function(str)
	{
		var regExp = /^\d+$/g;
		return regExp.test(str);
	}
	
	/**
	* 把日期分割成数组 [年、月、日、时、分、秒]
	*/
	this.toArray = function(myDate)  
	{   
		myDate = arguments[0] || new Date();
		var myArray = Array();  
		myArray[0] = myDate.getFullYear();  
		myArray[1] = myDate.getMonth();  
		myArray[2] = myDate.getDate();  
		myArray[3] = myDate.getHours();  
		myArray[4] = myDate.getMinutes();  
		myArray[5] = myDate.getSeconds();  
		return myArray;  
	}  
	
	/**
	* 取得日期数据信息  
	* 参数 interval 表示数据类型  
	* y 年 M月 d日 w星期 ww周 h时 n分 s秒  
	*/
	this.datePart = function(interval, myDate)  
	{   
		myDate = arguments[1] || new Date();
		var partStr='';  
		var Week = ['日','一','二','三','四','五','六'];  
		switch (interval)  
		{   
			case 'y' :partStr = myDate.getFullYear();break;  
			case 'M' :partStr = myDate.getMonth()+1;break;  
			case 'd' :partStr = myDate.getDate();break;  
			case 'w' :partStr = Week[myDate.getDay()];break;  
			case 'ww' :partStr = myDate.WeekNumOfYear();break;  
			case 'h' :partStr = myDate.getHours();break;  
			case 'm' :partStr = myDate.getMinutes();break;  
			case 's' :partStr = myDate.getSeconds();break;  
		}  
		return partStr;  
	}  
	
	/**
	* 取得当前日期所在月的最大天数  
	*/
	this.maxDayOfDate = function(date)  
	{   
		date = arguments[0] || new Date();
		date.setDate(1);
		date.setMonth(date.getMonth() + 1);
		var time = date.getTime() - 24 * 60 * 60 * 1000;
		var newDate = new Date(time);
		return newDate.getDate();
	}
};

/**
* 对象转url参数
* @param {*} data
* @param {*} isPrefix
*/
util.queryParams = function(data, isPrefix) {
	isPrefix = isPrefix ? isPrefix : false
	let prefix = isPrefix ? '?' : ''
	let _result = []
	for (let key in data) {
	  let value = data[key]
	  // 去掉为空的参数
	  if (['', undefined, null].includes(value)) {
		continue
	  }
	  if (value.constructor === Array) {
		value.forEach(_value => {
		  _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value))
		})
	  } else {
		_result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
	  }
	}

	return _result.length ? prefix + _result.join('&') : ''
}

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.修改所有style里的width属性为max-width:100%
 * 3.img标签添加style属性：max-width:100%;height:auto
 * 4.去掉<br/>标签
 * @param html
 * @return string
 */
util.formatRichText = function(html) {
	if(html != null){
		// 去掉img标签里的style、width、height属性
		let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
			match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
			match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
			match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
			return match;
		});
		// 修改所有style里的width属性为max-width:100%
		newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
			match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
			return match;
		});
		// 去掉<br/>标签
		newContent = newContent.replace(/<br[^>]*\/>/gi, '');
		// img标签添加style属性：max-width:100%;height:auto
		newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin:0px auto;"');
		return newContent;
	}else{
		return html;
	}
},

// 判断是否在微信中 
util.isWechat = function() {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/micromessenger/i) == 'micromessenger') {
		// console.log('是微信客户端')
		return true;
	} else {
		// console.log('不是微信客户端')
		return false;
	}
},

module.exports = util;